package com.kexun.common.utils;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtils {

    public static void main(String[] args) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\18137\\Desktop\\data.xlsx");
        Column[] columns = {
                new Column("name", "姓名"),
                new Column("sex", "性别")
        };
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", "李冬");
        map.put("sex", "男");
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("name", "李玩");
        map1.put("sex", "男");
        list.add(map);
        list.add(map1);
        XSSFWorkbook excel = createExcel(columns, list);
        excel.write(fileOutputStream);
        fileOutputStream.close();
    }


    public static XSSFWorkbook createExcel(Column[] title, List<Map<String, Object>> data) {
        XSSFWorkbook wb = new XSSFWorkbook();
        // 2.在workbook中添加一个sheet,对应Excel文件中的sheet
        XSSFSheet sheet = wb.createSheet("sheet1");
        XSSFRow row = sheet.createRow(0);
        for (int i = 0; i < title.length; i++) {
            Column column = title[i];
            row.createCell(i).setCellValue(column.getTitle());
        }
        for (int i = 0; i < data.size(); i++) {
            Map<String, Object> map = data.get(i);
            row = sheet.createRow(i + 1);
            for (int j = 0; j < title.length; j++) {
                Column column = title[j];
                String property = column.getProperty();
                row.createCell(j).setCellValue(map.get(property) + "");
            }
        }
        return wb;
    }


}
